// pages/review/review.js
const request = require('../../utils/request');
const Toast = require('../../utils/toast');

Page({
  data: {
    productId: null,
    orderNo: null,
    productName: '',
    rating: 5,
    content: '',
    images: [],
    submitting: false
  },

  onLoad(options) {
    if (options.productId && options.orderNo) {
      this.setData({
        productId: options.productId,
        orderNo: options.orderNo,
        productName: decodeURIComponent(options.productName || '')
      });
    } else {
      Toast.error('参数错误');
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 设置评分
  setRating(e) {
    const rating = e.currentTarget.dataset.rating;
    this.setData({ rating });
  },

  // 输入评价内容
  onContentInput(e) {
    this.setData({
      content: e.detail.value
    });
  },

  // 选择图片
  chooseImage() {
    const remainCount = 3 - this.data.images.length;
    if (remainCount <= 0) {
      Toast.error('最多上传3张图片');
      return;
    }

    wx.chooseMedia({
      count: remainCount,
      mediaType: ['image'],
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFiles = res.tempFiles || [];
        this.uploadImages(tempFiles);
      }
    });
  },

  // 上传图片
  async uploadImages(files) {
    Toast.loading('上传中...');
    
    try {
      const uploadedUrls = [];
      
      for (const file of files) {
        const uploadRes = await this.uploadSingleImage(file.tempFilePath);
        if (uploadRes) {
          uploadedUrls.push(uploadRes);
        }
      }

      Toast.hideLoading();

      if (uploadedUrls.length > 0) {
        this.setData({
          images: [...this.data.images, ...uploadedUrls]
        });
        Toast.success('上传成功');
      }
    } catch (error) {
      Toast.hideLoading();
      console.error('上传失败:', error);
      Toast.error('上传失败，请重试');
    }
  },

  // 上传单个图片
  uploadSingleImage(filePath) {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('token');
      const uploadUrl = `${request.baseUrl}/admin/products/upload-image`;

      wx.uploadFile({
        url: uploadUrl,
        filePath: filePath,
        name: 'image',
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            if (data.success && data.data && data.data.url) {
              resolve(data.data.url);
            } else {
              reject(new Error(data.message || '上传失败'));
            }
          } catch (error) {
            reject(error);
          }
        },
        fail: reject
      });
    });
  },

  // 删除图片
  removeImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.images.filter((_, i) => i !== index);
    this.setData({ images });
  },

  // 提交评价
  async submitReview() {
    const { productId, orderNo, rating, content, images } = this.data;

    if (!content || content.trim() === '') {
      Toast.error('请输入评价内容');
      return;
    }

    if (content.length < 5) {
      Toast.error('评价内容至少5个字');
      return;
    }

    this.setData({ submitting: true });
    Toast.loading('提交中...');

    try {
      const res = await request.post('/reviews', {
        product_id: productId,
        order_no: orderNo,
        rating: rating,
        content: content.trim(),
        images: images
      });

      Toast.hideLoading();

      if (res.success) {
        Toast.success('评价成功');
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        this.setData({ submitting: false });
        Toast.error(res.message || '评价失败');
      }
    } catch (error) {
      Toast.hideLoading();
      this.setData({ submitting: false });
      console.error('提交评价失败:', error);
      Toast.error('网络错误，请重试');
    }
  }
});

